Opa: Up and Running by Henri Binsztok Adam Koprowski & Ida Swarczewskaja

Opa: Up and Running by Henri Binsztok Adam Koprowski & Ida Swarczewskaja

Author:Henri Binsztok, Adam Koprowski & Ida Swarczewskaja
Language: eng
Format: epub, pdf
Tags: COMPUTERS / Web / Web Programming
ISBN: 9781449328801
Publisher: O’Reilly Media
Published: 2013-02-26T05:00:00+00:00


That seems like a useful definition, but we may need null for values of types other than just int. Repeating it for every single type where we need this feature would be terribly inefficient.

Fortunately, we can do better. Here is a definition from the standard Opa library:

type option('a) = {none} or {'a some}

Here, 'a is a type variable (type variables always begin with a single apostrophe) and the definition of option is parameterized by this type variable. It has two variants: {none}, meaning no value, and {some: x}, representing an existing value x of the parameterized type 'a.

We call such a type a polymorphic type as we can substitute the type variable, 'a, with an arbitrary type to obtain a concrete type. For instance, you can get optional integers by instantiating 'a with int to obtain option(int).

Also note that, thanks to Opa’s type inference, you will not need to spell out the type names in many cases. If you just write {some: 5}, the compiler will be able to figure out that this is a value of type option(int).

It’s important to realize that you can also write polymorphic functions like this one:



Download



Copyright Disclaimer:
This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.